package com.ljsw.view;

import com.ljsw.util.BitmapUtil;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/** 实现画板功能的View */
public class HuaBanView extends View {

	/** 缓冲位图 */
	private Bitmap cacheBitmap;
	/** 缓冲位图的画板 */
	private Canvas cacheCanvas;
	/** 缓冲画笔 */
	private Paint paint;
	/** 保存绘制曲线路径 */
	private Path path;
	/** 画布高 */
	private int height;
	/** 画布宽 */
	private int width;

	/** 保存上一次绘制的终点横坐标 */
	private float pX;
	/** 保存上一次绘制的终点纵坐标 */
	private float pY;

	/** 画笔初始颜色 */
	private int paintColor = Color.BLACK;
	/** 线状状态 */
	private static Paint.Style paintStyle = Paint.Style.STROKE;
	/** 画笔粗细 */
	private static int paintWidth = 3;

	private String filePath;

	/** 获取View实际宽高的方法 */
	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		height = h;
		width = w;
	}

	private void init() {
		paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		path = new Path();
		paint.setColor(paintColor);
		paint.setStyle(paintStyle);
		paint.setStrokeWidth(paintWidth);
	}

	public void setBackgroud(String filePath) {
		this.filePath = filePath;
	}

	public Bitmap getCachebBitmap() {
		return cacheBitmap;

	}

	public HuaBanView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public HuaBanView(Context context) {
		super(context);

	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		int action = event.getAction();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			path.moveTo(event.getX(), event.getY());
			pX = event.getX();
			pY = event.getY();
			break;
		case MotionEvent.ACTION_MOVE:
			path.quadTo(pX, pY, event.getX(), event.getY());
			pX = event.getX();
			pY = event.getY();
			break;
		case MotionEvent.ACTION_UP:
			cacheCanvas.drawPath(path, paint);
			path.reset();
			break;
		}
		invalidate();

		return true;
	}

	@Override
	protected void onDraw(Canvas canvas) {

		if (cacheBitmap == null) {
			cacheBitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
			cacheCanvas = new Canvas(cacheBitmap);
			Bitmap bitmap = BitmapUtil.getSmallBitmap(filePath);
			RectF rectF = new RectF(0, 0, width, height);
			cacheCanvas.drawBitmap(bitmap, null, rectF, null);
		}
		canvas.drawBitmap(cacheBitmap, 0, 0, paint);
		canvas.drawPath(path, paint);

	}

	/** 清空画布 */
	public void clearScreen() {
		if (cacheCanvas != null) {
			Bitmap bitmap = BitmapUtil.getSmallBitmap(filePath);
			RectF rectF = new RectF(0, 0, width, height);
			cacheCanvas.drawBitmap(bitmap, null, rectF, null);
		}
		invalidate();

	}

}
